<template>
  <div class="game-view">
    <div class="game-container">
      <!-- 游戏画布 -->
      <GameCanvas
        ref="gameCanvasRef"
        :width="canvasWidth"
        :height="canvasHeight"
        :auto-start="true"
        @engine-ready="handleEngineReady"
        @engine-error="handleEngineError"
        @key-down="handleKeyDown"
        @key-up="handleKeyUp"
        @canvas-click="handleCanvasClick"
      />
      
      <!-- 游戏UI -->
      <GameUI
        :score="gameState.score"
        :distance="gameState.distance"
        :health="gameState.health"
        :max-health="gameState.maxHealth"
        :power-ups="gameState.activePowerUps"
        :paused="gameState.isPaused"
        :show-mobile-controls="isMobileDevice"
        @toggle-pause="togglePause"
        @show-menu="showMenu"
        @restart-game="restartGame"
        @go-to-menu="goToMenu"
        @mobile-input="handleMobileInput"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useGameStore } from '@/stores/gameStore'
import GameCanvas from '@/components/GameCanvas.vue'
import GameUI from '@/components/GameUI.vue'
import type { GameEngine } from '@/game'

/**
 * 游戏视图组件
 * 管理游戏状态和用户交互
 * @component
 */

const router = useRouter()
const gameStore = useGameStore()

// 组件引用
const gameCanvasRef = ref<InstanceType<typeof GameCanvas>>()

// 游戏引擎实例
let gameEngine: GameEngine | null = null

// 画布尺寸
const canvasWidth = ref(800)
const canvasHeight = ref(400)

// 游戏状态
const gameState = reactive({
  score: 0,
  distance: 0,
  health: 100,
  maxHealth: 100,
  isPaused: false,
  activePowerUps: [] as Array<{
    type: string
    name: string
    remainingTime: number
  }>
})

// 计算属性
const isMobileDevice = computed(() => {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
})

/**
 * 创建玩家
 */
const createPlayer = (): void => {
  if (!gameEngine) return
  
  try {
    // 动态导入Player类
    import('@/game/Player').then(({ Player }) => {
      const player = new Player({
        x: canvasWidth.value / 2 - 25, // 居中
        y: canvasHeight.value * 0.8 - 50, // 地面上方
        width: 50,
        height: 50,
        groundY: canvasHeight.value * 0.8,
        laneWidth: 100
      })
      
      gameEngine!.addPlayer(player)
      console.log('玩家已创建并添加到游戏中')
    }).catch(error => {
      console.error('创建玩家失败:', error)
      // 创建一个简单的测试实体作为替代
      console.log('使用简化玩家替代')
    })
  } catch (error) {
    console.error('创建玩家时出错:', error)
  }
}

/**
 * 处理游戏引擎就绪事件
 * @param engine - 游戏引擎实例
 */
const handleEngineReady = (engine: GameEngine): void => {
  gameEngine = engine
  console.log('游戏引擎已就绪')
  
  // 创建并添加玩家
  createPlayer()
  
  // 设置游戏状态更新回调
  setupGameStateCallbacks()
  
  // 开始游戏
  startGame()
}

/**
 * 处理游戏引擎错误事件
 * @param error - 错误对象
 */
const handleEngineError = (error: Error): void => {
  console.error('游戏引擎错误:', error)
  // 可以显示错误提示给用户
}

/**
 * 设置游戏状态更新回调
 */
const setupGameStateCallbacks = (): void => {
  if (!gameEngine) return
  
  // 这里应该设置游戏引擎的回调函数来更新UI状态
  // 由于GameEngine的具体实现可能还没有这些回调，我们先模拟
  
  // 模拟游戏状态更新
  const updateInterval = setInterval(() => {
    if (gameEngine && !gameState.isPaused) {
      gameState.score += Math.floor(Math.random() * 10)
      gameState.distance += 0.5
      
      // 模拟道具效果
      gameState.activePowerUps = gameState.activePowerUps.filter(powerUp => {
        powerUp.remainingTime -= 0.1
        return powerUp.remainingTime > 0
      })
    }
  }, 100)
  
  // 清理定时器
  onUnmounted(() => {
    clearInterval(updateInterval)
  })
}

/**
 * 开始游戏
 */
const startGame = (): void => {
  if (!gameEngine) return
  
  // 重置游戏状态
  gameState.score = 0
  gameState.distance = 0
  gameState.health = gameState.maxHealth
  gameState.isPaused = false
  gameState.activePowerUps = []
  
  // 更新游戏存储状态
  gameStore.startGame()
  
  console.log('游戏开始')
}

/**
 * 切换暂停状态
 */
const togglePause = (): void => {
  gameState.isPaused = !gameState.isPaused
  
  if (gameEngine) {
    if (gameState.isPaused) {
      gameEngine.pause()
      gameStore.pauseGame()
    } else {
      gameEngine.resume()
      gameStore.resumeGame()
    }
  }
  
  console.log(gameState.isPaused ? '游戏暂停' : '游戏继续')
}

/**
 * 显示菜单
 */
const showMenu = (): void => {
  // 暂停游戏
  if (!gameState.isPaused) {
    togglePause()
  }
}

/**
 * 重新开始游戏
 */
const restartGame = (): void => {
  if (gameEngine) {
    gameEngine.stop()
    startGame()
    gameEngine.start()
  }
  console.log('重新开始游戏')
}

/**
 * 返回菜单
 */
const goToMenu = async (): Promise<void> => {
  try {
    // 停止游戏引擎
    if (gameEngine) {
      gameEngine.stop()
    }
    
    // 更新游戏存储状态
    gameStore.endGame()
    
    // 跳转到主菜单
    await router.push('/')
  } catch (error) {
    console.error('返回菜单失败:', error)
  }
}

/**
 * 处理键盘按下事件
 * @param event - 键盘事件
 */
const handleKeyDown = (event: KeyboardEvent): void => {
  if (gameState.isPaused) return
  
  switch (event.code) {
    case 'Space':
      // 跳跃
      handleGameAction('jump')
      break
    case 'ArrowDown':
      // 滑铲
      handleGameAction('slide')
      break
    case 'ArrowLeft':
      // 向左移动
      handleGameAction('moveLeft')
      break
    case 'ArrowRight':
      // 向右移动
      handleGameAction('moveRight')
      break
    case 'Escape':
      // 暂停游戏
      togglePause()
      break
  }
}

/**
 * 处理键盘释放事件
 * @param event - 键盘事件
 */
const handleKeyUp = (_event: KeyboardEvent): void => {
  // 处理按键释放逻辑
}

/**
 * 处理画布点击事件
 * @param event - 鼠标事件
 */
const handleCanvasClick = (event: MouseEvent): void => {
  // 点击画布时聚焦，确保能接收键盘事件
  if (event.target instanceof HTMLCanvasElement) {
    event.target.focus()
  }
}

/**
 * 处理移动端输入
 * @param action - 动作类型
 * @param pressed - 是否按下
 */
const handleMobileInput = (action: string, pressed: boolean): void => {
  if (!pressed || gameState.isPaused) return
  
  handleGameAction(action)
}

/**
 * 处理游戏动作
 * @param action - 动作类型
 */
const handleGameAction = (action: string): void => {
  if (!gameEngine) return
  
  // 这里应该调用游戏引擎的相应方法
  // 由于具体的GameEngine实现可能还没有这些方法，我们先记录日志
  console.log(`执行游戏动作: ${action}`)
  
  // 模拟一些游戏效果
  switch (action) {
    case 'jump':
      console.log('角色跳跃')
      break
    case 'slide':
      console.log('角色滑铲')
      break
    case 'moveLeft':
    case 'left':
      console.log('角色向左移动')
      break
    case 'moveRight':
    case 'right':
      console.log('角色向右移动')
      break
  }
}

/**
 * 调整画布大小 - 全屏模式
 */
const resizeCanvas = (): void => {
  // 全屏模式下，画布应该填充整个屏幕
  const screenWidth = window.innerWidth
  const screenHeight = window.innerHeight
  
  // 设置画布为全屏尺寸
  canvasWidth.value = screenWidth
  canvasHeight.value = screenHeight
  
  console.log(`画布尺寸调整为: ${screenWidth} x ${screenHeight}`)
}

// 处理窗口大小变化
const handleResize = (): void => {
  resizeCanvas()
}

/**
 * 进入全屏模式
 */
const enterFullscreen = async (): Promise<void> => {
  try {
    const element = document.documentElement
    if (element.requestFullscreen) {
      await element.requestFullscreen()
    } else if ((element as any).webkitRequestFullscreen) {
      await (element as any).webkitRequestFullscreen()
    } else if ((element as any).msRequestFullscreen) {
      await (element as any).msRequestFullscreen()
    }
    console.log('已进入全屏模式')
  } catch (error) {
    console.warn('无法进入全屏模式:', error)
  }
}

/**
 * 退出全屏模式
 */
const exitFullscreen = async (): Promise<void> => {
  try {
    if (document.exitFullscreen) {
      await document.exitFullscreen()
    } else if ((document as any).webkitExitFullscreen) {
      await (document as any).webkitExitFullscreen()
    } else if ((document as any).msExitFullscreen) {
      await (document as any).msExitFullscreen()
    }
    console.log('已退出全屏模式')
  } catch (error) {
    console.warn('无法退出全屏模式:', error)
  }
}

/**
 * 处理全屏状态变化
 */
const handleFullscreenChange = (): void => {
  const isFullscreen = !!(document.fullscreenElement || 
                          (document as any).webkitFullscreenElement || 
                          (document as any).msFullscreenElement)
  
  if (isFullscreen) {
    console.log('全屏模式已激活')
    // 调整画布大小以适应全屏
    setTimeout(() => {
      resizeCanvas()
    }, 100)
  } else {
    console.log('全屏模式已退出')
  }
}

// 生命周期钩子
onMounted(async () => {
  // 自动进入全屏模式
  await enterFullscreen()
  
  // 设置初始画布大小
  resizeCanvas()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
  
  // 监听全屏状态变化
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.addEventListener('msfullscreenchange', handleFullscreenChange)
  
  console.log('游戏视图已挂载，全屏模式已启用')
})

onUnmounted(async () => {
  // 退出全屏模式
  await exitFullscreen()
  
  // 清理事件监听器
  window.removeEventListener('resize', handleResize)
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.removeEventListener('msfullscreenchange', handleFullscreenChange)
  
  // 停止游戏引擎
  if (gameEngine) {
    gameEngine.stop()
    gameEngine = null
  }
  
  console.log('游戏视图已卸载，全屏模式已退出')
})
</script>

<style lang="scss" scoped>
@import '@/styles/responsive.scss';

.game-view {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #000;
  z-index: 1000;
  
  // 确保真正的全屏
  @include mobile-all {
    height: 100vh;
    height: -webkit-fill-available;
    // 隐藏地址栏和状态栏
    min-height: 100vh;
    min-height: -webkit-fill-available;
  }

  .game-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    display: block;
    
    // 移动端真正全屏
    @include mobile-all {
      // 覆盖整个屏幕
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      width: 100vw;
      height: 100vh;
      height: -webkit-fill-available;
      margin: 0;
      padding: 0;
      border-radius: 0;
    }
    
    // 桌面端也使用全屏
    @include desktop-all {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      width: 100vw;
      height: 100vh;
      margin: 0;
      border-radius: 0;
      box-shadow: none;
    }
  }
}

// 全屏模式样式
.game-view.fullscreen {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
  z-index: 9999 !important;
  
  .game-container {
    position: absolute !important;
    top: 0 !important;
    left: 0 !important;
    right: 0 !important;
    bottom: 0 !important;
    width: 100% !important;
    height: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
    border-radius: 0 !important;
    box-shadow: none !important;
  }
}

// 隐藏浏览器UI元素
@supports (display: -webkit-box) {
  .game-view {
    -webkit-appearance: none;
  }
}

// PWA全屏支持
@media (display-mode: fullscreen) {
  .game-view {
    height: 100vh;
    height: -webkit-fill-available;
  }
}

// 横屏优化
@media (orientation: landscape) {
  .game-view {
    .game-container {
      width: 100vw;
      height: 100vh;
    }
  }
}
</style>